//
//  JDRecruitViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/2/20.
//

import UIKit
import JXSegmentedView
import ProgressHUD
/// 招募
class JDRecruitViewController: JDBaseViewController {

    var superVC: JDMainScreenViewController?
    
    var myTableView: UITableView?
    var jdRecruitModels: [JDRecruitModel?]?
    
    var stateIndex: Int = 1
    
    var isFirstLoad: Bool = true
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFirstLoad == false && JDSingle.default.needRefreshDragonBoard {
            JDSingle.default.needRefreshDragonBoard = false
            self.getNetData(true, self.stateIndex, true)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        NotificationCenter.default.addObserver(self, selector: #selector(refreshTotalNum(_:)), name:  NSNotification.Name("refreshTotalNum"), object: nil)
//
//        NotificationCenter.default.addObserver(self, selector: #selector(notificationRefresh), name: Notification.Name("notificationRefresh"), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshTotalNum(_:)), name:  NSNotification.Name("refreshBoard"), object: nil)
        
//        self.getCurrentLocation()
        self.setupUIElements()
        
        self.getNetData(true, self.stateIndex, true)
        
        self.isFirstLoad = false
        // Do any additional setup after loading the view.
    }
    
    func setupUIElements() {
        self.myTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.myTableView!)
        self.myTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(0)
            make.bottom.equalTo(self.view).offset(0)
        })
        self.myTableView?.separatorStyle = .none
        self.myTableView?.delegate = self
        self.myTableView?.dataSource = self
        self.myTableView?.register(JDGridTableViewCell.self, forCellReuseIdentifier: "myCell")
        self.myTableView?.backgroundColor = color("#F5F6F8")
        
//        self.myTableView?.tableHeaderView = self.customHeaderView()
        
        self.myTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.superVC?.getTotalRegisterCount()
            self?.getNetData(true, self?.stateIndex ?? 0, true)
        }
        
        self.myTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false, self?.stateIndex ?? 0, true)
        }
        
    }
    
    @objc func refreshTotalNum(_ notify: Notification) {
        
        let info = notify.userInfo
        let stateIndex = (info?["stateIndex"] as? Int) ?? 0
        self.stateIndex = stateIndex
        self.getNetData(true, self.stateIndex, false)
    }
    
    func getNetData(_ isRefresh: Bool = true,_ searchStatus: Int = 1,_ needLoading:Bool = true) {
        // 当前页面接口
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        params["businessCode"] = "303"
        params["publishStatus"] = searchStatus
        if needLoading {
            ProgressHUD.animate()
        }
        JDNetWorkRequest(.bussiInfo(params)) { responseStr in
            print("请求成功:\(responseStr)")
            ProgressHUD.dismiss()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                if let recruitModels = [JDRecruitModel].deserialize(from: responseStr, designatedPath: "data.records") {
                    if isRefresh {
                        // 刷新
                        self.jdRecruitModels = recruitModels
                    } else {
                        // 加载
                        self.jdRecruitModels?.append(contentsOf: recruitModels)
                    }
                    if recruitModels.count < 10 {
                        self.myTableView?.reloadData()
                        self.myTableView?.noMoreData()
                        return
                    }
                } else {
                    self.myTableView?.reloadData()
                    self.myTableView?.noMoreData()
                    return 
                }
            }
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
        } failure: { error in
            print("请求失败")
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
            ProgressHUD.dismiss()
        } error: { errorCode in
            print("失败\(errorCode)")
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
            ProgressHUD.dismiss()
        }
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
}

extension JDRecruitViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}

extension JDRecruitViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.jdRecruitModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDMainScreenCell
//        
//        let currentModel = self.jdRecruitModels?[indexPath.row]
//        cell?.recruitModel = currentModel
////        cell?.contentLabel?.text = currentModel?.context
////        cell?.authorInfoLabel?.text = "联系人"+(currentModel?.lxr ?? "")
//        
//        return cell!
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDGridTableViewCell
        
        let currentModel = self.jdRecruitModels?[indexPath.row]
        cell?.recruitModel = currentModel

        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
}
